<template>
  <v-form v-model="valid" ref="myuserForm">
    <v-layout wrap>
      <v-text-field v-model="user.username" label="请输入用户名" required :rules="nameRules" />
      <v-text-field v-model="user.truename" label="请输入用户姓名" required />
    </v-layout>
    <v-layout horizontal>
      <v-text-field type="password" v-model="user.password" label="请输入用户密码" required />
      <v-select
        prepend-icon=" "
        v-model="user.lx"
        item-text="name"
        item-value="code"
        :items="aulist"
        label="请输入用户类型"
        required
      />
    </v-layout>
    <v-layout>
      <v-select
        v-model="user.storeCode"
        item-text="storeName"
        item-value="storeCode"
        :items="stores"
        @change="change"
        label="店铺"
        required
      />
    </v-layout>
    <v-layout>
      <v-select
        v-model="user.storageCode"
        item-text="storeName"
        item-value="storeCode"
        :items="stores"
        @change="change"
        label="仓库"
        required
      />
    </v-layout>
    <v-layout>
      <v-btn label class="primary" @click="selectAll">全选</v-btn>
    </v-layout>
    <v-layout class="my-4" horizontal>
      <v-data-table
        width="100%"
        style="height:100%; overflow:auto;"
        height="200"
        :headers="headers"
        class="elevation-1"
        show-select="true"
        v-model="selected"
        hide-actions
        item-key="plbm"
        :items="items"
        :loading="loading"
        :pagination="false"
      >
        <template slot="items" slot-scope="props">
          <td>
            <v-checkbox primary v-model="props.selected" hide-details></v-checkbox>
          </td>
          <td class="text-xs-center">{{ props.item.plbm }}</td>
          <td class="text-xs-center">{{ props.item.plmc }}</td>
        </template>
      </v-data-table>
    </v-layout>
    <!-- <v-checkbox v-model="checkbox" :label="`启用`"></v-checkbox> -->
    <v-layout class="my-4" row>
      <v-spacer />
      <v-btn @click="submit">保存</v-btn>
      <v-btn @click="clear">重置</v-btn>
      <v-btn v-if="!!this.isEdit" @click="remove">删除</v-btn>
    </v-layout>
  </v-form>
</template>

<script>
export default {
  name: "user-form",
  props: {
    oldBrand: {
      type: Object
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      pagination: {}, // 分页信息
      valid: false, // 表单校验结果标记
      user: {
        code: "", // 用户logo
        password: "",
        lx: "",
        deptCode: "",
        storaCode: "",
        pl: []
      },
      selected: [],
      aulist: [
        { name: "系统管理员", code: 0 },
        { name: "营业员", code: 1 },
        { name: "录入员", code: 2 },
        { name: "库管", code: 3 },
        { name: "司机", code: 4 },
        { name: "调度员", code: 5 },
        { name: "卖区长", code: 6 },
        { name: "业种经理", code: 7 },
        { name: "物流中心经理", code: 8 },
        { name: "家电公司经理", code: 9 }
      ],
      nameRules: [v => !!v || "用户名称不能为空"],
      checkbox: false,
      stores: [],
      depts: [],
      loading: false,
      items: [],
      headers: [
        { text: "选择", align: "center", sortable: false, value: "plbm" },
        { text: "品类编码", align: "center", sortable: false, value: "plbm" },
        { text: "品类名称", align: "center", sortable: false, value: "pimc" }
      ]
    };
  },
  methods: {
    selectAll() {
      this.selected = this.items;
    },
    getDataFromServer() {
      this.$http.get("/item/user/store").then(res => {
        this.stores = res.data;
      });

      this.$http.get("/item/user/dept").then(res => {
        this.depts = res.data;
      });

      this.$http.get("/item/item/pl?level=3").then(res => {
        this.items = res.data;
      });
    },
    change(e) {},

    remove() {
        const { ...params } = this.user;
        params.pl = this.selected;
        this.$http({
          method: "post",
          url: "/item/user/del",
          data: JSON.stringify(params),
          headers: {
            "Content-Type": "application/json;charset=UTF-8"
          }
        })
          .then(() => {
            // 关闭窗口
            this.$emit("close");
            this.$message.success("删除用户成功！");
            this.selected = [];
          })
          .catch(() => {
            this.$message.error("删除用户失败！");
          });
    },
    submit() {
      // 表单校验
      if (this.$refs.myuserForm.validate()) {
        // 定义一个请求参数对象，通过解构表达式来获取brand中的属性
        const { ...params } = this.user;
        // let pls = [];
        // params.pl.forEach(element => {
        // pls.push({ plbm: element });
        // });
        params.pl = this.selected;
        // params.status = this.checkbox ? 1 : 2;
        // 数据库中只要保存分类的id即可，因此我们对categories的值进行处理,只保留id，并转为字符串
        // params.cids = items.map(c => c.id).join(",");
        // 将字母都处理为大写
        //params.letter = letter.toUpperCase();
        // 将数据提交到后台
        // this.$http.post('/item/brand', this.$qs.stringify(params))

        this.$http({
          method: "post",
          url: this.isEdit ? "/item/user/update" : "/item/user/insert",
          data: JSON.stringify(params),
          headers: {
            "Content-Type": "application/json;charset=UTF-8"
          }
        })
          .then(() => {
            // 关闭窗口
            this.$emit("close");
            this.$message.success("保存成功！");
            this.selected = [];
          })
          .catch(() => {
            this.$message.error("保存失败！");
          });
      }
    },
    clear() {
      // 重置表单
      this.$refs.myuserForm.reset();
    }
  },
  watch: {
    oldBrand: {
      // 监控oldBrand的变化
      handler(val) {
        this.getDataFromServer();
        if (val) {
          // 注意不要直接复制，否则这边的修改会影响到父组件的数据，copy属性即可

          this.user = Object.deepCopy(val);

          this.selected = this.user.pl;

          this.items = this.user.pl;
        } else {
          // 为空，初始化brand
          this.user = {
            username: "",
            truename: "",
            password: "",
            lx: "",
            storeCode: "",
            deptCode: "",
            pl: []
          };
        }
        // this.selected = this.user.pl;
      },

      deep: true
    }
  }
};
</script>

<style scoped>
</style>
